package com.bifrost.service.impl;

import com.bifrost.constant.OrderTransactionType;
import com.bifrost.entity.Order;
import com.bifrost.entity.OrderTransaction;
import com.bifrost.model.vo.OrderTransactionVO;
import com.bifrost.model.vo.PageVO;
import com.bifrost.repository.OrderTransactionRepository;
import com.bifrost.service.AdminOrderTransactionService;
import com.bifrost.util.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

@Service("adminOrderTransactionService")
public class AdminOrderTransactionServiceImpl implements AdminOrderTransactionService {


    @Autowired
    OrderTransactionRepository orderTransactionRepository;

    /**
     * 分页查询订单售后信息
     * @param pageCode
     * @param pageSize
     * @return
     */
    @Override
    public PageVO list(String orderNumber, String startTime, String endTime, Integer pageCode, Integer pageSize) {
        Pageable pageable = new PageRequest(pageCode-1, pageSize, new Sort(Sort.Direction.DESC, "transactionId"));
        Specification<OrderTransaction> specification = new Specification<OrderTransaction>() {
            @Override
            public Predicate toPredicate(Root<OrderTransaction> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                //订单流水 只显示付款和退款记录
                predicates.add(cb.notEqual(root.get("transactionType"), OrderTransactionType.JSPAY));
                if(!StringUtils.isBlank(orderNumber)){
                    //增加查询条件：订单号
                    Join<OrderTransaction,Order> join = root.join("order", JoinType.INNER);
                    Path<String> queryOrderNum = join.get("orderNumber");
                    predicates.add(cb.like(queryOrderNum,"%"+orderNumber.trim()+"%"));
                    //predicates.add(cb.like(root.get("orderCode"),"%"+orderNumber.trim()+"%"));
                }
                if(!StringUtils.isBlank(startTime)){
                    //增加查询条件：开始时间
                    predicates.add(cb.greaterThanOrEqualTo(root.get("transactionDate"), DateUtils.parse(startTime, DateUtils.DEFAULT_DATE_FORMAT)));
                }
                if(!StringUtils.isBlank(endTime)){
                    //增加查询条件：结束时间
                    predicates.add(cb.lessThanOrEqualTo(root.get("transactionDate"), DateUtils.parse(endTime, DateUtils.DEFAULT_DATE_FORMAT)));
                }
                Predicate[] p = new Predicate[predicates.size()];
                return cb.and(predicates.toArray(p));
            }
        };
        Page<OrderTransaction> page = orderTransactionRepository.findAll(specification, pageable);
        Long totalElement = page.getTotalElements();
        List<OrderTransactionVO> orderTransactionVOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("######0.00");
        for(OrderTransaction orderTransaction : page.getContent()){
            OrderTransactionVO orderTransactionVO = new OrderTransactionVO();
            BeanUtils.copyProperties(orderTransaction,orderTransactionVO);
            String amount = String.valueOf(df.format(Double.parseDouble(orderTransaction.getTransactionAmount())/100));
            if(OrderTransactionType.REFUND.equalsIgnoreCase(orderTransaction.getTransactionType()))
                amount = "-".concat(amount);
            orderTransactionVO.setTransactionAmount(amount);
            //设置transactionDat
            orderTransactionVO.setTransactionDate(DateUtils.formatDate(orderTransaction.getTransactionDate(), DateUtils.DEFAULT_DATE_FORMAT));
            //设置orderMessage
            Order order = orderTransaction.getOrder();
            if(order == null){
                throw new RuntimeException("订单号查询失败");
            }
            orderTransactionVO.setOrderId(order.getOrderId());
            orderTransactionVO.setOrderCode(order.getOrderNumber());
            orderTransactionVO.setOutTradeNo(order.getOutTradeNo());
            orderTransactionVOList.add(orderTransactionVO);
        }
        PageVO pageVO = new PageVO(pageCode,pageSize,totalElement.intValue(),orderTransactionVOList);
        return pageVO;
    }
}
